﻿using System;
using Elasticsearch.Synchronize.Common.Enum;
using Elasticsearch.Synchronize.Job.Tailer.Setting;
using Elasticsearch.Synchronize.Common.Entity;

using Nest;
using HYService.RabbitMQ;

namespace Elasticsearch.Synchronize.Job.Tailer
{
    public class EventJoinTailer : BaseTailer
    {
        private readonly EventJoinOption _option;

        public EventJoinTailer(EventJoinOption option) : base(option.ElasticsearchUrl)
        {
            _option = option;
        }

        public void Run()
        {
            Console.WriteLine("开始啦");

            RabbitHub.Subscribe<EventJoinContext>(_option.QueueName, (msg) =>
            {
                var data = msg.EventJoin;

                switch (msg.OpType)
                {
                    case OperateType.Add:
                        _elasticClient.Index(data,
                            r => r.Id(data._id).Index(_option.IndexName)
                                .Type(_option.TypeName));
                        break;
                    case OperateType.Update:
                        _elasticClient.Index(data,
                            r => r.Id(data._id).Index(_option.IndexName)
                                .Type(_option.TypeName));
                        break;
                    case OperateType.Delete:
                        _elasticClient.Delete(new DeleteRequest(_option.IndexName,
                            _option.TypeName, msg.Id));
                        break;
                }
            });
        }
    }
}